package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;

@Component
@Slf4j
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
public class SupplyTaskHandler implements MsgHandler  {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        try {
            var supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
            if(supplyContract == null) return;

            VmVO vmInfo = vmService.getVMInfo(supplyContract.getInnerCode());
            int userId = taskService.getLeastUser(vmInfo.getRegionId(), false);
            var viewModel = new TaskViewModel();
            viewModel.setUserId(userId);
            viewModel.setDesc("自动补货订单");
            viewModel.setCreateType(0);
            viewModel.setInnerCode(supplyContract.getInnerCode());
            viewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
            viewModel.setDetails(
                    supplyContract.getSupplyData().stream().map(s -> {
                        var taskDetailsViewModel = new TaskDetailsViewModel();
                        taskDetailsViewModel.setChannelCode(s.getChannelId());
                        taskDetailsViewModel.setExpectCapacity(s.getCapacity());
                        taskDetailsViewModel.setSkuId(s.getSkuId());
                        taskDetailsViewModel.setSkuImage(s.getSkuImage());
                        taskDetailsViewModel.setSkuName(s.getSkuName());
                        return taskDetailsViewModel;
                    }).collect(Collectors.toList())
            );
            taskService.create(viewModel);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建自动补货工单出错"+e.getMessage());
        }
    }
}
